import java.util.LinkedList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 * https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
 */
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int n = matrix.length, m = matrix[0].length;
        int left = 0, right = m - 1, top = 0, bottom = n - 1, count = n * m;
        List<Integer> ret = new LinkedList<>();

        while (left <= right && top <= bottom) {
            //从左到右
            for(int i = left; i <= right; i++) {
                ret.add(matrix[top][i]);
            }
            top++;
            //从上到下
            for(int i = top; i <= bottom; i++) {
                ret.add(matrix[i][right]);
            }
            right--;
            //从右到左
            if(top <= bottom) {
                for(int i = right; i >= left; i--) {
                    ret.add(matrix[bottom][i]);
                }
            }
            bottom--;
            //从下到上
            if(left <= right) {
                for(int i = bottom; i >= top; i--) {
                    ret.add(matrix[i][left]);
                }
            }
            left++;
        }

        return ret;
    }
}